package com.qywx.utils;

import com.qywx.entity.DepartmentEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DeptTree
 * @Description: TODO
 * @Author wmj
 * @Date 2020/3/13
 * @Version V1.0
 **/
public class DeptTree {

    private List<DepartmentEntity> menuList = new ArrayList<DepartmentEntity>();

    public DeptTree(List<DepartmentEntity> menuList) {
        this.menuList = menuList;
    }

    //建立树形结构
    public List<DepartmentEntity> builTree() {
        List<DepartmentEntity> treeMenus = new ArrayList<DepartmentEntity>();
        for (DepartmentEntity menuNode : getRootNode()) {
            menuNode.setLabel(menuNode.getName());
            menuNode = buildChilTree(menuNode);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private DepartmentEntity buildChilTree(DepartmentEntity pNode) {
        List<DepartmentEntity> chilMenus = new ArrayList<DepartmentEntity>();
        for (DepartmentEntity menuNode : menuList) {
            menuNode.setLabel(menuNode.getName());
            if (menuNode.getParentid().equals(pNode.getId())) {
                chilMenus.add(buildChilTree(menuNode));
            }
        }
        pNode.setChildren(chilMenus);
        return pNode;
    }

    //获取根节点
    private List<DepartmentEntity> getRootNode() {
        List<DepartmentEntity> rootMenuLists = new ArrayList<DepartmentEntity>();
        for (DepartmentEntity menuNode : menuList) {
            if (menuNode.getParentid()==0l) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}
